/**
 * title: 填写法人代表信息
 */
import React, { Component } from 'react';
import { Form, Input, Row, Col, message, DatePicker, Icon } from 'antd';
import { OssUpload, UploadImageSample } from 'scd';
import EditBox from './components/EditBox';
import Wrapper from './components/Wrapper';
import { connect } from 'dva';
import getFileId from '@/utils/getFileId';
import Actions from './components/Actions';
import moment from 'moment';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;

@Form.create()
@connect(({ createCompany: { companyInformation }, loading: { models: { createCompany } } }) => ({
  companyInformation,
  loading: !!createCompany,
}))
class LegalRepresentative extends Component {
  componentDidMount() {
    const {
      location: {
        query: { temId },
      },
      dispatch,
    } = this.props;
    if (temId) {
      dispatch({
        type: 'createCompany/queryForm',
        payload: {
          temId,
          step: 2,
        },
      }).catch(errMsg => {
        message.error(errMsg);
      });
    }
  }

  handleChange = ({ fileList }) => this.setState({ fileList });

  handleSubmit = type => e => {
    e.preventDefault();
    const {
      form,
      dispatch,
      history,
      location: {
        query: { temId },
      },
    } = this.props;
    form.validateFieldsAndScroll((err, fieldsValue) => {
      if (!err) {
        let values = {
          ...fieldsValue,
          legalParValStaTime: fieldsValue.legalParValTime[0].format('YYYY-MM-DD'),
          legalParValEndTime: fieldsValue.legalParValTime[1].format('YYYY-MM-DD'),
          id: temId,
          temType: 1,
          legalPerFacePhoto: getFileId(fieldsValue.legalPerFacePhoto),
          legalPerBackPhoto: getFileId(fieldsValue.legalPerBackPhoto),
        };

        dispatch({
          type: 'createCompany/saveForm',
          payload: values,
        })
          .then(id => {
            message.success('操作成功');
            type === 'submit' && history.push(`/createCompany/AgentInformation?temId=${id}`);
          })
          .catch(errMsg => {
            message.error(errMsg);
          });
      }
    });
  };
  goBack = () => {
    const { dispatch, history } = this.props;
    dispatch({
      type: 'createCompany/removeLocalForm',
    });
    history.goBack();
  };
  normFile = e => {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  render() {
    const {
      form: { getFieldDecorator, getFieldValue },
      loading,
      companyInformation,
      dispatch,
      location: {
        query: { temId },
      },
    } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };
    const formItemLayout2 = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
    };
    const rangeConfig = {
      initialValue: companyInformation.legalParValStaTime
        ? [
            moment(companyInformation.legalParValStaTime),
            moment(companyInformation.legalParValEndTime),
          ]
        : undefined,
      rules: [{ type: 'array', required: true, message: '请选择证件有效期' }],
    };
    return (
      <Wrapper
        current={1}
        loading={loading}
        actions={
          <Actions
            temId={temId}
            dispatch={dispatch}
            goBack={this.goBack}
            handleSave={this.handleSubmit('save')}
            handleSubmit={this.handleSubmit('submit')}
          />
        }
      >
        <EditBox title="法人代表信息（必填）" description={' '}>
          <Form onSubmit={this.handleSubmit}>
            <Row>
              <Col span={12}>
                <FormItem label="归属地" {...formItemLayout}>
                  {getFieldDecorator('legalPersonRegister', {
                    initialValue: companyInformation.legalPersonRegister,
                    rules: [
                      {
                        required: true,
                        message: '请输入归属地',
                      },
                    ],
                  })(<Input placeholder="请输入归属地" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem label="姓名" {...formItemLayout}>
                  {getFieldDecorator('legalPersonName', {
                    initialValue: companyInformation.legalPersonName,
                    rules: [
                      {
                        required: true,
                        message: '请输入姓名',
                      },
                    ],
                  })(<Input placeholder="请输入姓名" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem label="身份证" {...formItemLayout}>
                  {getFieldDecorator('legalPersonCode', {
                    initialValue: companyInformation.legalPersonCode,
                    rules: [
                      {
                        required: true,
                        message: '请输入身份证',
                      },
                    ],
                  })(<Input placeholder="请输入身份证" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem label="证件有效期" {...formItemLayout}>
                  {getFieldDecorator('legalParValTime', rangeConfig)(
                    <RangePicker style={{ width: '100%' }} placeholder={['起始时间', '结束时间']} />
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem label="联系方式" {...formItemLayout}>
                  {getFieldDecorator('legalPersonPhone', {
                    initialValue: companyInformation.legalPersonPhone,
                    rules: [
                      {
                        required: true,
                        message: '请输入联系方式',
                      },
                    ],
                  })(<Input placeholder="请输入联系方式" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem {...formItemLayout} label="上传证件">
                  支持.png .pdf .jpg格式上传，大小5m以内
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={6}>
                <FormItem {...formItemLayout2} label=" " colon={false}>
                  {getFieldDecorator('legalPerFacePhoto', {
                    valuePropName: 'fileList',
                    getValueFromEvent: this.normFile,
                    initialValue: companyInformation.legalPerFacePhoto,
                    rules: [
                      {
                        required: true,
                        message: '请上传证件正面',
                      },
                    ],
                  })(
                    <OssUpload
                      listType="picture-card"
                      data={{
                        businessId: 0,
                        businessType: 'string',
                        companyId: 0,
                        digestMethod: 1,
                        ext: '',
                        moduleCode: 'company',
                        productLineId: 0,
                        userId: 1,
                      }}
                    >
                      {getFieldValue('legalPerFacePhoto') &&
                      getFieldValue('legalPerFacePhoto').length === 1 ? null : (
                        <UploadButton>上传证件正面</UploadButton>
                      )}
                    </OssUpload>
                  )}
                </FormItem>
              </Col>
              <Col span={4}>
                <UploadImageSample />
              </Col>
              <Col span={3}>
                <FormItem {...formItemLayout2}>
                  {getFieldDecorator('legalPerBackPhoto', {
                    valuePropName: 'fileList',
                    getValueFromEvent: this.normFile,
                    initialValue: companyInformation.legalPerBackPhoto,
                    rules: [
                      {
                        required: true,
                        message: '请上传证件反面',
                      },
                    ],
                  })(
                    <OssUpload
                      listType="picture-card"
                      data={{
                        businessId: 0,
                        businessType: 'string',
                        companyId: 0,
                        digestMethod: 1,
                        ext: '',
                        moduleCode: 'company',
                        productLineId: 0,
                        userId: 1,
                      }}
                    >
                      {getFieldValue('legalPerBackPhoto') &&
                      getFieldValue('legalPerBackPhoto').length === 1 ? null : (
                        <UploadButton>上传证件反面</UploadButton>
                      )}
                    </OssUpload>
                  )}
                </FormItem>
              </Col>
              <Col span={4}>
                <UploadImageSample />
              </Col>
            </Row>
          </Form>
        </EditBox>
      </Wrapper>
    );
  }
}
const UploadButton = ({ children }) => (
  <div>
    <Icon type="plus" />
    <div className="ant-upload-text" style={{ paddingTop: 10 }}>
      {children}
    </div>
  </div>
);
export default LegalRepresentative;
